package com.intelligent.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intelligent.pojo.ProductionWarehousing;
import com.intelligent.service.ProductionWarehousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/productionWarehousing")
public class ProductionWarehousingController {

    @Autowired
    private ProductionWarehousingService productionWarehousingService;

    /**
     * 分页查询生产入库记录
     * 
     * @param current 当前页码，默认1
     * @param size 每页大小，默认10
     * @param warehousingNo 入库单号（可选）
     * @param warehousingStatus 入库状态（可选）
     * @param workOrderNo 工单编号（可选）
     * @param warehouseId 仓库ID（可选）
     * @param uId 入库人ID（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 分页结果
     */
    @GetMapping("/page")
    public Map<String, Object> getProductionWarehousingPage(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String warehousingNo,
            @RequestParam(required = false) Integer warehousingStatus,
            @RequestParam(required = false) String workOrderNo,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Integer uId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建分页对象
            Page<ProductionWarehousing> page = new Page<>(current, size);
            
            // 执行分页查询
            IPage<ProductionWarehousing> pageResult = productionWarehousingService.getProductionWarehousingPage(
                    page, warehousingNo, warehousingStatus, workOrderNo, 
                    warehouseId, uId, startTime, endTime
            );
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", pageResult);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }

    /**
     * 根据ID查询生产入库记录详情（包含关联信息）
     * 
     * @param id 入库记录ID
     * @return 入库记录详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getProductionWarehousingById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 根据ID查询入库记录详情
            ProductionWarehousing productionWarehousing = productionWarehousingService.getProductionWarehousingById(id);
            
            if (productionWarehousing != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", productionWarehousing);
            } else {
                result.put("code", 404);
                result.put("message", "未找到对应的入库记录");
                result.put("data", null);
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }

    /**
     * 新增生产入库记录
     * 
     * @param productionWarehousing 生产入库记录信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public Map<String, Object> addProductionWarehousing(@RequestBody ProductionWarehousing productionWarehousing) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数校验
            if (productionWarehousing.getWorkOrderId() == null) {
                result.put("code", 400);
                result.put("message", "关联工单ID不能为空");
                result.put("data", null);
                return result;
            }
            
            if (productionWarehousing.getWarehouseId() == null) {
                result.put("code", 400);
                result.put("message", "入库仓库ID不能为空");
                result.put("data", null);
                return result;
            }
            
            if (productionWarehousing.getQuantity() == null || productionWarehousing.getQuantity() <= 0) {
                result.put("code", 400);
                result.put("message", "入库数量必须大于0");
                result.put("data", null);
                return result;
            }
            
            if (productionWarehousing.getUId() == null) {
                result.put("code", 400);
                result.put("message", "入库人ID不能为空");
                result.put("data", null);
                return result;
            }
            
            // 设置默认入库状态（如果未指定）
            if (productionWarehousing.getWarehousingStatus() == null) {
                productionWarehousing.setWarehousingStatus(2); // 默认为全部入库
            }
            
            // 执行新增操作
            boolean success = productionWarehousingService.addProductionWarehousing(productionWarehousing);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "新增成功");
                result.put("data", productionWarehousing);
            } else {
                result.put("code", 500);
                result.put("message", "新增失败");
                result.put("data", null);
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "新增失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }

    /**
     * 修改生产入库记录
     * 
     * @param productionWarehousing 生产入库记录信息（必须包含id）
     * @return 操作结果
     */
    @PutMapping("/update")
    public Map<String, Object> updateProductionWarehousing(@RequestBody ProductionWarehousing productionWarehousing) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数校验
            if (productionWarehousing.getId() == null) {
                result.put("code", 400);
                result.put("message", "入库记录ID不能为空");
                result.put("data", null);
                return result;
            }
            
            // 检查记录是否存在
            ProductionWarehousing existingRecord = productionWarehousingService.getProductionWarehousingById(productionWarehousing.getId());
            if (existingRecord == null) {
                result.put("code", 404);
                result.put("message", "未找到对应的入库记录");
                result.put("data", null);
                return result;
            }
            
            // 如果更新数量，需要校验数量必须大于0
            if (productionWarehousing.getQuantity() != null && productionWarehousing.getQuantity() <= 0) {
                result.put("code", 400);
                result.put("message", "入库数量必须大于0");
                result.put("data", null);
                return result;
            }
            
            // 执行更新操作
            boolean success = productionWarehousingService.updateProductionWarehousing(productionWarehousing);
            
            if (success) {
                // 查询更新后的记录详情
                ProductionWarehousing updatedRecord = productionWarehousingService.getProductionWarehousingById(productionWarehousing.getId());
                result.put("code", 200);
                result.put("message", "修改成功");
                result.put("data", updatedRecord);
            } else {
                result.put("code", 500);
                result.put("message", "修改失败");
                result.put("data", null);
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "修改失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }

    /**
     * 删除生产入库记录
     * 
     * @param id 入库记录ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteProductionWarehousing(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数校验
            if (id == null) {
                result.put("code", 400);
                result.put("message", "入库记录ID不能为空");
                result.put("data", null);
                return result;
            }
            
            // 检查记录是否存在
            ProductionWarehousing existingRecord = productionWarehousingService.getProductionWarehousingById(id);
            if (existingRecord == null) {
                result.put("code", 404);
                result.put("message", "未找到对应的入库记录");
                result.put("data", null);
                return result;
            }
            
            // 执行删除操作
            boolean success = productionWarehousingService.deleteProductionWarehousing(id);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "删除成功");
                result.put("data", null);
            } else {
                result.put("code", 500);
                result.put("message", "删除失败");
                result.put("data", null);
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
}
